package actions;

import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.Action;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JPopupMenu;
import javax.swing.JTextPane;

import textArea.AwesomeTextPanel;

import frame.AwesomeFrame;

/**
 * AwesomeMenuActions are used exclusively in Menus.
 * AwesomeMenuActions allow the action to access elements of the frame they are in using
 * the functionality specific to this class.
 * 
 * @author Brittin
 *
 *
 */
public abstract class AwesomeMenuAction extends AbstractAction {
	
	public AwesomeMenuAction(String name, String desc)
	{
		putValue(Action.NAME, name);
		putValue(Action.SHORT_DESCRIPTION, desc);
	}
	
	/**
	 * Returns the parent frame of the source which invoked this action.
	 * @param e The ActionEvent that invoked this action.
	 * @return the parent frame of the source which invoked this action.
	 */
	protected AwesomeFrame getParentFrame(ActionEvent e) {
		if (e != null) {
			Object source = e.getSource();
			
			// Surely the source is a component, but we should be sure when casting.
			// We must cast to a component to navigate to the parent of source.
			if (source instanceof Component) {
				
				Component current = (Component) source;
				// Loop until we locate the frame.
				while (true) {
					if ( current == null ) {
						break;
					} else if ( current instanceof AwesomeFrame ) {
						return (AwesomeFrame) current;
					} else if ( current instanceof JPopupMenu ) {
						// This case must be handled differently, as a JPopupMenu 
						// may not have a parent.
						current = ((JPopupMenu) current).getInvoker();
					} else {
						current = current.getParent();
					}
				}
			}
		}
		return null;
	}
	
	/**
	 * Returns the currently selected JTextPane of the parent frame
	 *  of the source which invoked this action.
	 * @param e The ActionEvent that invoked this action.
	 * @return the currently selected JTextPane of the parent frame
	 *  of the source which invoked this action.
	 */
	protected JTextPane getSelectedTextPane(ActionEvent e) {
		return this.getParentFrame(e).getTextPane();
	}
	
	/**
	 * Returns the currently selected AwesomeTextPanel of the parent frame
	 *  of the source which invoked this action.
	 * @param e The ActionEvent that invoked this action.
	 * @return the currently selected AwesomeTextPanel of the parent frame
	 *  of the source which invoked this action.
	 */
	protected AwesomeTextPanel getSelectedTextPanel(ActionEvent e) {
		return this.getParentFrame(e).getTextPanel();
	}
	
	/**
	 * Returns the file chooser used by the parent frame.
	 * @param e The ActionEvent that invoked this action.
	 * @return the file chooser used by the parent frame.
	 */
	protected JFileChooser getFileChooser(ActionEvent e) {
		return this.getParentFrame(e).getFileChooser();
	}
}
